<template>
	<el-dialog :visible.sync="modelValue" :title="'打印机设置'" width="30%" height="700" append-to-body
		:modal-append-to-body="false" :close-on-click-modal="false" top="5vh" custom-class="casc-dialog">
		<div class="content">
			<el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px" class="printer-form">
				<el-form-item label="打印机" prop="title">
					<el-input v-model="formData.title" placeholder="请输入打印机名称" class="full-width-input" />
				</el-form-item>
				<el-form-item label="IP地址" prop="ip">
					<el-input v-model="formData.ip" placeholder="请输入打印机IP" class="full-width-input" />
				</el-form-item>
				<el-form-item label="打印单据">
					<div class="flex_between">
						<el-select v-model="formData.ch" placeholder="请选择打印单据类型（可多选）" class="widths-input" multiple
							filterable clearable>
							<el-option v-for="item in printerData.ch_ls" :key="item.id" :label="item.title"
								:value="item.id" />
						</el-select>
						<span class="font_size12 font_black9">已选：{{ formData.ch.length || 0 }}</span>
					</div>
				</el-form-item>
				<el-form-item label="打印云店">
					<div class="flex_between">
						<el-select v-model="formData.shopid_yds" placeholder="请选择打印云店（可多选）" class="widths-input"
							multiple filterable clearable>
							<el-option v-for="item in printerData.idyun_ls" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
						<span class="font_size12 font_black9">已选：{{ formData.shopid_yds.length || 0 }}</span>
					</div>
				</el-form-item>
				<el-form-item label="打印门店">
					<div class="flex_between">
						<el-select v-model="formData.shopids" placeholder="请选择打印门店（可多选）" class="widths-input" multiple
							filterable clearable>
							<el-option v-for="item in printerData.shop_ls" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
						<span class="font_size12 font_black9">已选：{{ formData.shopids.length || 0 }}</span>
					</div>
				</el-form-item>
				<el-form-item label="打印仓库">
					<div class="flex_between">
						<el-select v-model="formData.storeids" placeholder="请选择打印仓库（可多选）" class="widths-input" multiple
							filterable clearable>
							<el-option v-for="item in printerData.store_ls" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
						<span class="font_size12 font_black9">已选：{{ formData.storeids.length || 0 }}</span>
					</div>
				</el-form-item>
				<el-form-item label="启用">
					<el-switch v-model="formData.status" :active-value="1" :inactive-value="2" active-color="#409EFF"
						inactive-color="#C0CCDA" />
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<div class="flex_between">
				<div>
					<el-button class="font_red" v-if="isType == 'edt'" type="text" @click="deletePrinter"
						size="mini">删除该打印机</el-button>
				</div>
				<div>
					<el-button @click="close" size="mini"> 取 消 </el-button>
					<el-button type="primary" @click="handleSubmit('ae')" size="mini"> 确 定 </el-button>
				</div>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref, onMounted, defineExpose, defineProps, getCurrentInstance, defineEmits } from '@vue/composition-api'
import config from "@/js/conf/Config.js"

const { proxy } = getCurrentInstance()

// 定义props，接收打印机数据用于编辑模式
const props = defineProps({
	printerData: {
		type: Object,
		default: () => { }
	},
})
const emit = defineEmits(['success-handle'])

// 定义弹窗引用
const formRef = ref(null)
const modelValue = ref(false)
const isType = ref('add')
// 表单数据 - 下拉框字段改为数组类型以支持多选
const formData = ref({
	title: '',
	ip: '',
	ch: [], // 改为数组类型
	shopid_yds: [],   // 改为数组类型
	shopids: [],       // 改为数组类型
	storeids: [],   // 改为数组类型
	status: 1,
})

// 表单验证规则
const formRules = ref({
	title: [
		{ required: true, message: '请输入打印机名称', trigger: 'blur' }
	],
	ip: [
		{ required: true, message: '请输入打印机IP', trigger: 'blur' },
		{
			pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
			message: '请输入有效的IP地址',
			trigger: 'blur'
		}
	]
})

// 初始化表单数据（编辑模式）
onMounted(() => {
	// 如果是编辑模式，处理传入的printerData
})

// 提交表单
const handleSubmit = async (type = 'ae') => {
	const valid = await proxy.$refs.formRef.validate()
	if (!valid) {
		proxy.$message({
			message: '请完善表单信息',
			type: 'warning'
		})
		return
	}
	try {
		let params = {
			...formData.value,
		}
		if (type == 'del') {
			params.status = 2
		}
		let res = await proxy.$api({ url: config.compset_printer_save, data: params })
		if (res.status == 1) {
			if (type == 'ae') {
				proxy.$message({
					message: '操作成功',
					type: 'success'
				})
				emit('success-handle', res.data)
				close()
			}
		}
	} catch (error) {
		console.error('提交表单失败:', error)
	}
}

const deletePrinter = () => {
	proxy.$confirm('确定删除该打印机吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		await handleSubmit('del')
		let res = await proxy.$api({ url: config.compset_printer_del, data: { id: formData.value.id } })
		if (res.status == 1) {
			proxy.$message({
				message: '操作成功',
				type: 'success'
			})
			emit('success-handle', res.data)
			close()
		}
	}).catch(() => {
		// 取消删除
	});
}

const close = () => {
	modelValue.value = false
}

const resetForm = () => {
	formData.value = {
		title: '',
		ip: '',
		ch: [], // 改为数组类型
		shopid_yds: [],   // 改为数组类型
		shopids: [],       // 改为数组类型
		storeids: [],   // 改为数组类型
		status: 1,
	}
}

defineExpose({
	show: (data) => {
		isType.value = data.type || 'add'
		if (data.type == 'edt') {
			formData.value = data.infoData
		} else {
			resetForm()
		}
		modelValue.value = true
	},
	resetForm,
	close
})
</script>

<style lang="scss">
.casc-dialog {
	.el-dialog__body {
		padding: 0px !important;
	}
}
</style>

<style scoped lang="scss">
.content {
	padding: 10px;
	overflow-y: auto;
	max-height: 550px;
}

.printer-form {
	width: 100%;
}

.full-width-input {
	width: 100%;
}

.widths-input {
	flex: 1;
	margin-right: 5px;
}

.flex_between {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

/* 优化多选下拉框的样式 */
:deep(.el-select) {
	.el-select__tags {
		flex-wrap: wrap;
	}

	.el-select__input {
		min-width: 60px;
	}
}
</style>